<template>
  <a-layout>
    <top-bar/>
    <a-layout-content :style="{padding: '0 26px', marginTop: '64px', minHeight: '600px'}">
      <a-spin style="margin-top: 60px" v-if="loddingVisible" :indicator="indicator" />
      <a-result v-if="err_5xxVisible" status="500" title="500" sub-title="Sorry, the server is wrong.">
        <template #extra>
          <router-link to="/">
            <a-button type="primary">去主页</a-button>
          </router-link>
        </template>
      </a-result>
      <div v-if="allVisible">
        <a-row :gutter="16" justify="space-around" align="middle" style="margin-top: 20px">
          <!--展示图片-->
          <a-col class="gutter-row" :span="8">
            <a-carousel arrows :after-change="onChange" >
              <template #prevArrow>
                <div class="custom-slick-arrow" style="left: 10px; z-index: 1">
                  <left-circle-outlined />
                </div>
              </template>
              <template #nextArrow>
                <div class="custom-slick-arrow" style="right: 10px">
                  <right-circle-outlined />
                </div>
              </template>
              <a-image v-for="img in imgs" :width="500" :src="img"/>
            </a-carousel>
          </a-col>

          <!-- 销售属性描述-->
          <a-col class="gutter-row" :span="16">
            <a-row :gutter="16" style="margin-top: 2px; margin-left: 5px">
              <a-col class="gutter-row" :span="24">
                <a-typography-title :level="3"> {{currentSku.skuTitle}} </a-typography-title>
              </a-col>
              <a-col class="gutter-row" :span="24">
                <a-typography-title :level="5"> {{currentSku.skuSubtitle}} </a-typography-title>
              </a-col>
              <a-col class="gutter-row" style="margin-top: 5px" :span="24">
                <a-descriptions bordered size="default" :span="4">
                  <template #extra>
                    <a-button type="primary" danger>购买</a-button>
                  </template>

                  <a-descriptions-item label="价格：">
                    <a-typography-text strong>
                      {{currentSku.price}}￥
                    </a-typography-text>
                  </a-descriptions-item>
                  <a-descriptions-item label="销量：">{{currentSku.saleCount}}件</a-descriptions-item>
                  <a-descriptions-item label="重量：">{{currentSpu.weight}}kg</a-descriptions-item>

                </a-descriptions>
              </a-col>
            </a-row>
            <!--描述销售属性-->
            <div style="background-color: #ececec; padding: 20px; margin-top: 10px">
              <a-card v-for="saleAttr in saleAttrs" :title="saleAttr.attrName">
                <a-card-grid v-for="value in saleAttr.values" style="width: 15%; text-align: center">
                  <a-button :type="checkType(value)" value="middle" @click="clickAttr(value, saleAttr.attrId)">
                    {{value.attrValue}}
                  </a-button>
                </a-card-grid>
              </a-card>
            </div>
            <a-space style="margin-top: 10px" size="large">
              <a-input-number v-model:value="number" size="large" :min="1" :max="100000" />
              <a-button type="primary" @click="addToShopcarItem" danger>加入购物车</a-button>
            </a-space>
          </a-col>
        </a-row>
        <div style="padding: 20px">
          <a-anchor
              direction="horizontal"
              :get-current-anchor="CurrentAnchor"
              @click="anchorClick"
              :items="[
                        {
                          key: 'horizontally-part-2',
                          href: '#/product/info/baseAttrs',
                          title: '规格与包装',
                        },
                        {
                          key: 'horizontally-part-1',
                          href: `#/ss`,
                          title: '商品介绍',
                        },
                        {
                          key: 'horizontally-part-3',
                          href: '#/product/info/comment',
                          title: '商品评论',
                        }
                      ]"
          />
          <router-view :toBaseAttr="baseAttrs"></router-view>
        </div>
      </div>

    </a-layout-content>
    <tail-bar/>
  </a-layout>
</template>

<script setup>
import router from "@/router";
import request from "@/utils/request";
import {ref, onMounted, onUpdated, h} from 'vue'
import TailBar from "@/components/common/TailBar.vue";
import TopBar from "@/components/common/TopBar.vue";
import { LeftCircleOutlined, RightCircleOutlined, LoadingOutlined  } from '@ant-design/icons-vue'
import {message} from "ant-design-vue";
import {publish} from "pubsub-js";

let skuId = router.currentRoute.value.query.skuId
let spuId = router.currentRoute.value.query.spuId

//添加到购物车的数量
let number = ref(1)
let currentAnchor = ref('#/product/info/baseAttrs')

let allVisible = ref(false)
let loddingVisible = ref(true)
let err_5xxVisible = ref(false)

let saleAttrs = ref([])  //存放spu下的销售属性
let currentSaleAttr = ref([]) //存放当前sku下的销售属性 [{attrId, attrName, value: {attrName, skuids}}]
let baseAttrs = ref([])

let currentSku = ref({})
let currentSpu = ref({})

let imgs = ref([])

const hoverImg = ()=>{
  console.log('hover')
}

//图片修改
const onChange = current => {
  console.log(current);
};

const getProductInfo = ()=>{
  allVisible.value = false
  loddingVisible.value = true
  err_5xxVisible.value = false
  request({
    url: `/product/skuinfo/search_info/${skuId}`,
    method: 'get'
  }).then(res => {
    console.log("响应数据", res)
    if(res.code === 0){
      allVisible.value = true
      loddingVisible.value = false
      currentSku.value = res.data.skuInfo
      imgs.value.splice(0, imgs.value.length)
      res.data.imags.forEach(item=>{
        imgs.value.push(item.imgUrl)
      })
      baseAttrs.value = res.data.baseAttrs

      currentSpu.value = res.data.spuInfo

      currentSaleAttr.value.splice(0, currentSaleAttr.value.length)
      saleAttrs.value.splice(0, saleAttrs.value.length)
      res.data.saleAttrs.forEach(item=>{
        saleAttrs.value.push(item)
        let temp = {attrId: item.attrId, attrName: item.attrName}
        for (let i = 0; i < item.values.length; i++) {
          if(item.values[i].skuIds.includes(skuId)){
            temp['value'] = item.values[i]
            break
          }
        }
        currentSaleAttr.value.push(temp)
      })
    }
  }).catch(err => {
    console.log("搜索商品详情异常", err.message)
    message.error("搜索商品详情异常", err.message)
    if(err.message.includes('50')){
      err_5xxVisible.value = true
    }
  }).finally(_=>{
    loddingVisible.value = false
  })
}

function checkType(value){
  if(value.skuIds.includes(skuId)){
    return 'primary'
  }else {
    return 'dashed'
  }
}

function clickAttr(value, attrId){
  let set1 = new Set
  value.skuIds.split(',').forEach(item=>{
    set1.add(item)
  })
  let collect = []
  //与其他销售属性做笛卡尔积得到最终要搜索的skuId
  currentSaleAttr.value.forEach(item => {
    if(item.attrId !== attrId){
      item.value.skuIds.split(',').forEach(skuId=>{
        if(set1.has(skuId)){
          collect.push(skuId)
        }
      })
    }
  })
  if(collect.length === 1){
    router.push({
      path: '/product/info/baseAttrs',
      query: {spuId, skuId: collect[0]}
    })
    skuId = collect[0]
    getProductInfo()
  }
}

const indicator = h(LoadingOutlined, {
  style: {
    fontSize: '30px',
  },
  spin: true,
});


const anchorClick = (e,link) => {
  if(typeof link === "undefined" || link === null || link === ''){
    return '#/product/info/baseAttrs';
  } else {
    currentAnchor.value = link.href
    return link
  }
};

const addToShopcarItem = ()=> {
  request({
    url: '/auth/user/shop-car/addItem',
    method: 'post',
    params: {skuId: currentSku.value.skuId, count: number.value}
  }).then(res => {
    console.log(res)
    if(res.code === 0){
      message.success("成功添加到购物车")
      //向子组件发送事件
      publish("addItem", '添加了购物项')
    }
  }).catch(err => {
    console.log(err.message)
  })
}

const CurrentAnchor = () => {
  return currentAnchor.value
}

onMounted(_=>{
  getProductInfo()
})
</script>

<style scoped>
/* For demo */
:deep(.slick-slide) {
  text-align: center;
  height: 500px;
  line-height: 160px;
  background: #575757;
  overflow: hidden;
}

:deep(.slick-arrow.custom-slick-arrow) {
  width: 25px;
  height: 25px;
  font-size: 25px;
  color: #6084a8;
  background-color: rgba(31, 45, 61, 0.11);
  transition: ease all 0.3s;
  opacity: 0.3;
  z-index: 1;
}
:deep(.slick-arrow.custom-slick-arrow:before) {
  display: none;
}
:deep(.slick-arrow.custom-slick-arrow:hover) {
  color: #fff;
  opacity: 0.5;
}

:deep(.slick-slide h3) {
  color: #fff;
}
</style>
